package com.zc.service;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.util.Properties;
import java.util.Random;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.util.Random;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zc.dao.QueryRunnerHelper;
import com.zc.utils.servletUtils;

/**
 * 处理请求类
 * @author yuZhe
 *
 */
public class Service {
	private QueryRunner runner=new QueryRunnerHelper().getRunner();//数据库操作类
	public int delete(String sql,Object... params) {
		try {
			return runner.execute(sql, params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;//数据库错误
		}
	}
	/**
	 * 获取邮箱验证码
	 * @param email
	 * @return 邮箱验证码
	 */
	public String getMailCaptach(String email){
		try {
			//0.1 设置基本参数
			Properties props = new Properties();
			//  设置主机
			props.setProperty("mail.host", "smtp.163.com");
			//  确定使用权限验证
			props.setProperty("mail.smtp.auth", "true");
			//0.2 确定账号与密码 
			Authenticator authenticator = new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					//return new PasswordAuthentication("设置将要登陆邮箱的账号（必须写上@后面的东西）", "设置授权码");
					return new PasswordAuthentication("zc206616201@163.com", "ZMOPJUWUGCHDUZTO");
				}
			};
			//1获得连接
			Session session = Session.getInstance(props, authenticator);
			//2 编写消息
			Message message = new MimeMessage(session);
			// 2.1 发件人
			//message.setFrom(new InternetAddress("设置发件人的邮箱","设置发件人的姓名，自己写"));
			message.setFrom(new InternetAddress("zc206616201@163.com", "zc"));
			
			// 2.2 收件人 , to:收件人   cc:抄送   bcc:暗送
			// message.setRecipient(RecipientType.TO, new InternetAddress("设置收件人的邮箱"));
			message.setRecipient(RecipientType.TO, new InternetAddress(email));
			
			//设置多个收件人地址
			//message.addRecipient(RecipientType.TO,new InternetAddress("设置收件人的邮箱"));
			
			// 2.3 主题
			message.setSubject("【穷游】您正在进行身份验证");
			// 2.4 正文，直接html代码的
			String captach="";
			Random r=new Random();
			for(int i=0;i<6;i++) {
				captach+=r.nextInt(9)+1;
			}
			message.setContent("【穷游】您正在进行身份验证，验证码："+captach, "text/html;charset=UTF-8");
			//3发送消息
			Transport.send(message);
			System.out.println("发送成功");
			return captach;
		} catch (Exception e) {
			// TODO: handle exception
			return null;//失败
		}
	}
	/**
	 * 更新数据库
	 * @param sql
	 * @param params
	 * @return -1数据库错误    其他：影响的行数
	 */
	public int updateDB(String sql,Object... params) {
		try {
			return runner.update(sql, params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;//数据库错误
		}
	}
	/**
	 * 查询结果的数量
	 * @param sql
	 * @return null异常 其他：查询结果数量
	 */
	public Long queryNum(String sql,Object... params) {
		Long num=null;
		try {
			num=runner.query(sql,new ScalarHandler<Long>(),params);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return num;
	}
	/**
	 * 查询并封装成JavaBean
	 * @return null异常
	 */
	public <T> List<T> queryJavaBean(Class<T> clas,String sql,Object... params) {
		try {
			return runner.query(sql,new BeanListHandler<T>(clas),params);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 获取短信验证码
	 * @return 验证码 （null表示未成功）
	 */
	public String getCaptcha(String phone) {
		String code="";
		DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4Fd9QnLzxkXsmxzWkEoi", "A2RHbxw01YBLIcIj6VlJoYfNnlMEdO");
        IAcsClient client = new DefaultAcsClient(profile);
        //短信平台有很多的
        //有的平台就不限制的
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "default");
        //发送到哪个手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名
        request.putQueryParameter("SignName", "穷游");
        request.putQueryParameter("TemplateCode", "SMS_186968590");
        Random r = new Random();
        for (int i = 0; i < 6; i++) {
        	code += r.nextInt(10);
		}
        request.putQueryParameter("TemplateParam", "{\"code\":"+code+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
            return null;
        } catch (ClientException e) {
        	e.printStackTrace();
        	return null;
        }catch (Exception e) {
        	e.printStackTrace();
        	return null;
        }
		 return code;
	}
    public static void main(String[] args) {
		Service s=new Service();
		s.getMailCaptach("1966374207@qq.com");
		
	}
}
